package com.uzai.console.service.fd.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.uzai.common.enums.DeviceTypeEnum;
import com.uzai.common.exception.BusinessException;
import com.uzai.common.result.ResponseCode;
import com.uzai.common.utils.EsIndexName;
import com.uzai.console.common.utils.DateUtil;
import com.uzai.console.common.utils.Tools;
import com.uzai.console.constant.ES.ESResult;
import com.uzai.console.constant.ES.ElasticsearchUtilGroupMsg;
import com.uzai.console.dto.fd.fdfollowgroup.FdFollowGroupIdDto;
import com.uzai.console.dto.fd.fdfollowgroup.FdFollowGroupMsgQuery;
import com.uzai.console.dto.fd.fdfollowgroup.FdFollowGroupQuery;
import com.uzai.console.dto.fd.fdsendjob.FdSendJobQuery;
import com.uzai.console.entity.Device;
import com.uzai.console.entity.FdDevicePlan;
import com.uzai.console.entity.FdFollowGroup;
import com.uzai.console.entity.FdSendJob;
import com.uzai.console.entity.es.EsFdFollowOfficialGroupMsg;
import com.uzai.console.entity.es.EsFdGroupSendMsg;
import com.uzai.console.mapper.FdDevicePlanMapper;
import com.uzai.console.mapper.FdFollowGroupMapper;
import com.uzai.console.service.device.DeviceService;
import com.uzai.console.service.fd.FdFollowGroupService;
import com.uzai.console.service.feign.UzaiImClientFeignService;
import com.uzai.console.service.merchant.MerchantService;
import com.uzai.console.vo.fd.fdfollowgroup.FdFollowGroupMsgVo;
import com.uzai.console.vo.fd.fdfollowgroup.FdFollowGroupVo;
import com.uzai.console.vo.fd.fdsendjob.FdSendJobSubVo;
import com.uzai.console.vo.fd.fdsendjob.FdSendMsgVo;
import org.apache.commons.lang3.StringUtils;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.TermQueryBuilder;
import org.elasticsearch.index.reindex.DeleteByQueryRequest;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.sort.SortOrder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * 发单跟发配置
 * @author liuqi
 * @date 2021年08月13日 11:34
 */
@Service
public class FdFollowGroupServiceImpl implements FdFollowGroupService {

    Logger logger = LoggerFactory.getLogger(FdFollowGroupServiceImpl.class);

    @Autowired
    private FdFollowGroupMapper fdFollowGroupMapper;
    @Autowired
    private UzaiImClientFeignService uzaiImClientFeignService;
    @Autowired
    private DeviceService deviceService;
    @Autowired
    private FdDevicePlanMapper fdDevicePlanMapper;
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private MerchantService merchantService;
    @Autowired
    private ElasticsearchUtilGroupMsg elasticsearchUtilGroupMsg;


    /**
     * 查询发单跟发配置列表
     * @author liuqi
     * @date 2021/8/13 11:38
     * @param fdFollowGroupQuery
     * @return null
     */
    public Page<FdFollowGroupVo> findFdFollowGroupList(FdFollowGroupQuery fdFollowGroupQuery){
        //新建返回到页面的LIST对象
        List<FdFollowGroupVo> fdFollowGroupPageVoList = new ArrayList<>();

        //执行分页查询对象
        Page<FdFollowGroup> page = new Page<>();
        fdFollowGroupQuery.convert(page);
        List<FdFollowGroup> fdFollowGroupList =  fdFollowGroupMapper.findByLit(page, fdFollowGroupQuery);
        if(fdFollowGroupList != null && fdFollowGroupList.size() > 0){
            for (FdFollowGroup fdFollowGroup : fdFollowGroupList){
                FdFollowGroupVo fdFollowGroupPageVo = new FdFollowGroupVo();
                BeanUtils.copyProperties(fdFollowGroup, fdFollowGroupPageVo);
                if(StringUtils.isNotBlank(fdFollowGroup.getPlatforms())){
                    try {
                        List<Integer> platformList = JSONObject.parseArray(fdFollowGroup.getPlatforms(), Integer.class);
                        fdFollowGroupPageVo.setPlatforms(platformList);
                    }catch (Exception e){

                    }
                }
                fdFollowGroupPageVoList.add(fdFollowGroupPageVo);
            }
        }
        //返回到页面分页对象
        Page<FdFollowGroupVo> pageVo = new Page<>();
        BeanUtils.copyProperties(page, pageVo);
        pageVo.setRecords(fdFollowGroupPageVoList);
        //将分页信息复制到返回到页面的分页MO当中
        return pageVo;
    }

    /**
     * 查询发单跟发配置详情
     * @author liuqi
     * @date 2021/8/13 11:38
     * @param fdFollowGroupIdDto
     * @return null
     */
    public FdFollowGroupVo findFdFollowGroup(FdFollowGroupIdDto fdFollowGroupIdDto){
        if(fdFollowGroupIdDto.getId() == null){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "id不能为空");
        }

        FdFollowGroup fdFollowGroup = fdFollowGroupMapper.selectById(fdFollowGroupIdDto.getId());

        if(fdFollowGroup == null ){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该发单跟发配置不存在");
        }

        FdFollowGroupVo fdFollowGroupVo = new FdFollowGroupVo();
        BeanUtils.copyProperties(fdFollowGroup, fdFollowGroupVo);

        if(StringUtils.isNotBlank(fdFollowGroup.getPlatforms())){
            try {
                List<Integer> platformList = JSONObject.parseArray(fdFollowGroup.getPlatforms(), Integer.class);
                fdFollowGroupVo.setPlatforms(platformList);
            }catch (Exception e){

            }
        }

        return fdFollowGroupVo;
    }

    /**
     * 查询官方采集群采集消息列表
     * @author liuqi
     * @date 2021/8/13 11:38
     * @param fdFollowGroupMsgQuery
     * @return null
     */
    public Page<FdFollowGroupMsgVo> findFdFollowGroupMsgList(FdFollowGroupMsgQuery fdFollowGroupMsgQuery){
        if(fdFollowGroupMsgQuery.getGroupWxid() == null){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "请输入群微信id");
        }

        //新建返回到页面的LIST对象
        List<FdFollowGroupMsgVo> fdFollowGroupMsgVoList = new ArrayList<>();

        //执行分页查询对象
        Page<FdFollowGroupMsgVo> page = new Page<>();
        fdFollowGroupMsgQuery.convert(page);

        //ES查询
        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
        BoolQueryBuilder boolQuery = QueryBuilders.boolQuery();

        //群wxid
        if(StringUtils.isNotBlank(fdFollowGroupMsgQuery.getGroupWxid())){
            boolQuery.must(QueryBuilders.termQuery("groupWxid.keyword", fdFollowGroupMsgQuery.getGroupWxid()));
        }

        //消息类型
        if(fdFollowGroupMsgQuery.getMsgType() != null){
            boolQuery.must(QueryBuilders.termQuery("msgType", fdFollowGroupMsgQuery.getMsgType()));
        }

        //查新开始时间
        if(fdFollowGroupMsgQuery.getCreateTimeStart() != null){
            boolQuery.must(QueryBuilders.rangeQuery("createTime").gte(fdFollowGroupMsgQuery.getCreateTimeStart()));
        }

        //查新结束时间
        if(fdFollowGroupMsgQuery.getCreateTimeEnd()!= null){
            boolQuery.must(QueryBuilders.rangeQuery("createTime").lte(fdFollowGroupMsgQuery.getCreateTimeEnd()));
        }

        searchSourceBuilder.query(boolQuery);

        //排序
        searchSourceBuilder.sort("createTime", SortOrder.DESC);

        //查询运营商其他索引分片
        String uzai_fd_follow_official_group_msg = EsIndexName.FD_FOLLOW_OFFICIAL_GROUP_MSG;
        ESResult esResult = elasticsearchUtilGroupMsg.searchListData(uzai_fd_follow_official_group_msg, searchSourceBuilder, fdFollowGroupMsgQuery.getSize(), fdFollowGroupMsgQuery.getFromIndex(), null, null, null, 1234567890L);
        page.setTotal(esResult.getTotalHits());
        List<Map<String, Object>> dataList = esResult.getDataList();
        if(dataList != null && dataList.size() > 0){
            for (Map<String, Object> dataMp :dataList) {
                EsFdFollowOfficialGroupMsg esFdFollowOfficialGroupMsg = JSONObject.parseObject(JSONObject.toJSONString(dataMp), EsFdFollowOfficialGroupMsg.class);
                FdFollowGroupMsgVo fdFollowGroupMsgVo = new FdFollowGroupMsgVo();
                if(esFdFollowOfficialGroupMsg != null){
                    BeanUtils.copyProperties(esFdFollowOfficialGroupMsg, fdFollowGroupMsgVo);
                    fdFollowGroupMsgVoList.add(fdFollowGroupMsgVo);
                }
            }
        }
        page.setRecords(fdFollowGroupMsgVoList);
        //将分页信息复制到返回到页面的分页MO当中
        return page;
    }

    /**
     * 删除官方采集群历史消息
     * @author liuqi
     * @date 2021/8/13 11:38
     * @param beforeDay
     * @return null
     */
    public void deleteFdFollowGroupMsgHistoryBeforeDay(Integer beforeDay){
        DeleteByQueryRequest deleteByQueryRequest = new DeleteByQueryRequest();
        //清空所有的发送明细
        SearchSourceBuilder searchSourceBuilder_del = new SearchSourceBuilder();
        BoolQueryBuilder boolQuery_and = new BoolQueryBuilder();
        //多少时间之前的历史消息
        boolQuery_and.must(QueryBuilders.rangeQuery("createTime").lte(beforeDay));
        searchSourceBuilder_del.query(boolQuery_and).size(100);
        deleteByQueryRequest.getSearchRequest().source(searchSourceBuilder_del);
        String uzai_fd_follow_official_group_msg = EsIndexName.FD_FOLLOW_OFFICIAL_GROUP_MSG;
        elasticsearchUtilGroupMsg.deleteDataByQueryMulti(uzai_fd_follow_official_group_msg, deleteByQueryRequest);
    }


}
